package yscmd

import (
	"gitee.com/kmyss/gf-ex/ysbuild"
	"gitee.com/kmyss/gf-ex/yslog"
	"gitee.com/kmyss/gf-ex/ysother"
	"github.com/gogf/gf/v2/container/gmap"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gcmd"
	"github.com/gogf/gf/v2/os/gfile"
	"github.com/gogf/gf/v2/os/glog"
)

// GetArgIndex 获取指定 Arg 对应的索引值
func GetArgIndex(a string) int {
	args := gcmd.GetArgAll()
	for i, arg := range args {
		if arg == a {
			return i
		}
	}
	return -1
}

// GetChildArg 获取指定 Arg 对应的 子命令
func GetChildArg(a string) string {
	index := GetArgIndex(a)
	if index == -1 {
		return ""
	} else {
		return gcmd.GetArg(index+1, "").String()
	}
}

// ScanVar 获取命令行输入的字符串转换为 Var 类型方便使用
func ScanVar(message string, defaultValue string) *g.Var {
	s := gcmd.Scanf("%s (默认值: %s) :", message, defaultValue)
	switch s {
	case "":
		return g.NewVar(defaultValue)
	default:
		return g.NewVar(s)
	}
}

// DefaultHelp 默认帮助函数， 可以不用覆盖
func DefaultHelp(c *Command) {
	yslog.DebugV("默认帮助函数")
	ysbuild.PrintAppInfo()
	c.PrintHelp()
}

// DefaultRun 默认执行函数，直接运行子命令
func DefaultRun(c *Command) {
	yslog.DebugV("默认执行函数")
	cmdStr := GetChildArg(c.Use)
	c.RunChildCmd(cmdStr)
}

func RootRun(c *Command) {
	if !IsShell(c.Context()) {
		yslog.Print("当前工作目录：", gfile.Pwd())

		ysother.ShowConfigPath()
		ysother.DebugConfig(c.Context())

		if FlagVerbose(c.Context()).Has() {
			g.Log().SetLevel(glog.LEVEL_ALL)
		}
	}

	cmdName := gcmd.GetArg(1).String()
	c.RunChildCmd(cmdName)

}

// SetDefaultCommand 设置命令默认命令 help 和 version
func SetDefaultCommand(parent ICommandBuilder) {
	SetChildCommand(parent, &CmdHelpBuilder{})
	SetChildCommand(parent, &CmdVersionBuilder{})
}

func NewDefaultCommand() *Command {
	cmd := &Command{
		commands: gmap.NewListMap(),
		flags:    gmap.NewListMap(),
	}
	return cmd
}

func NewCommandWithDefaultFunc() *Command {
	cmd := NewDefaultCommand()
	cmd.Help = DefaultHelp
	cmd.Run = DefaultRun
	return cmd
}

func Logger(c *Command) *glog.Logger {
	return nil
}
